package com.itcodai.controller.course12;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author c-fanqj
 * @date 2023/4/5
 * @apiNote 使用HttpSessionListener统计在线用户数的监听器
 * 2、监听HTTP会话 Session对象
 */
//@Component
public class MyHttpSessionListener  implements HttpSessionListener {

    private final Logger logger =
            LoggerFactory.getLogger(this.getClass());

    // 记录在线用户数量
    private Integer count = 0;

    @Override
    public synchronized void sessionCreated(HttpSessionEvent se) {
        logger.info("新用户上线了");
        count++;
        se.getSession().getServletContext().setAttribute("count", count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        logger.info("用户下线了");
        count--;
        se.getSession().getServletContext().setAttribute("count", count);
    }
}
